package cn.fws.meap.utils.logBug;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日志切面
 *
 * @author : jiang
 * @Date: 2018/12/21 11:41
 * @Description:
 */
@Aspect
@Component
public class LogAspect {

    @Pointcut("@annotation(cn.fws.meap.utils.logBug.SysLog))")
    public void logPointcut() {
    }

    @Before("logPointcut()")
    public void before(JoinPoint joinPoint) {

        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            SysLog logs = signature.getMethod().getAnnotation(SysLog.class);
            String value = logs.value();

            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String url = request.getRequestURL().toString();
            if (url.contains("api")) {
            } else {
                System.out.println("进入" + value + "接口");
                System.out.println("请求地址：" + request.getRequestURL());
                System.out.println("请求时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                System.out.println("请求ip：" + IpUtil.getIpAddress(request));
                JSONObject jsonObject = SpringUtil.getRequestParam(request);
                System.out.println("请求参数：" + jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @AfterReturning(value = "logPointcut()", returning = "keys")
    public void doAfterReturningAdvice1(JoinPoint joinPoint, Object keys) {

        if (keys == null) {
            System.out.println("接口返回参数：null");
        } else {
            System.out.println("接口返回参数：" + keys.toString());
        }
    }
}
